package servlets;

import com.google.gson.Gson;
import entity.ResponseData;
import entity.User;
import utils.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/users","/users/*"})
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        handleCors(response);
        response.setContentType("application/json;charset=UTF-8");

        String pathInfo = request.getPathInfo();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtils.getConnection();

            if (pathInfo == null || pathInfo.equals("/")) {
                // 获取所有用户列表
                String sql = "SELECT * FROM t_dormuser";
                pstmt = conn.prepareStatement(sql);
                rs = pstmt.executeQuery();

                List<User> users = new ArrayList<>();
                while (rs.next()) {
                    User user = new User(
                            rs.getInt("dormManId"),
                            rs.getString("userName"),
                            rs.getString("password")
                    );
                    user.setDormBuildId(rs.getInt("dormBuildId"));
                    users.add(user);
                }

                Gson gson = new Gson();
                String jsonResponse = gson.toJson(users);
                response.getWriter().write(jsonResponse);
            } else {
                // 获取特定用户详情
                String idStr = pathInfo.substring(1);
                try {
                    int userId = Integer.parseInt(idStr);

                    String sql = "SELECT * FROM t_dormuser WHERE dormManId = ?";
                    pstmt = conn.prepareStatement(sql);
                    pstmt.setInt(1, userId);
                    rs = pstmt.executeQuery();

                    if (rs.next()) {
                        User user = new User(
                                rs.getInt("dormManId"),
                                rs.getString("userName"),
                                rs.getString("password")
                        );
                        user.setDormBuildId(rs.getInt("dormBuildId"));

                        Gson gson = new Gson();
                        String jsonResponse = gson.toJson(user);
                        response.getWriter().write(jsonResponse);
                    } else {
                        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                        Gson gson = new Gson();
                        String jsonResponse = gson.toJson(new ResponseData(false, "用户未找到"));
                        response.getWriter().write(jsonResponse);
                    }
                } catch (NumberFormatException e) {
                }
            }
        } catch (Exception e) {
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        handleCors(response);
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        StringBuilder jsonBuffer = new StringBuilder();
        String line;
        try (BufferedReader reader = request.getReader()) {
            while ((line = reader.readLine()) != null) {
                jsonBuffer.append(line);
            }
        }

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            Gson gson = new Gson();
            User user = gson.fromJson(jsonBuffer.toString(), User.class);

            String sql = "INSERT INTO t_dormuser (userName, password, dormBuildId) VALUES (?, ?, ?)";
            conn = DBUtils.getConnection();
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, user.getUserName());
            pstmt.setString(2, user.getPassword());
            pstmt.setObject(3, user.getDormBuildId());

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        user.setId(generatedKeys.getInt(1));
                    }
                }
                String jsonResponse = gson.toJson(new ResponseData(true, "添加成功"));
                response.getWriter().write(jsonResponse);
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write(gson.toJson(new ResponseData(false, "添加失败")));
            }
        } catch (Exception e) {
        }
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        handleCors(response);
        response.setContentType("application/json;charset=UTF-8");

        String id = request.getPathInfo().substring(1);
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            int userId = Integer.parseInt(id);

            String sql = "DELETE FROM t_dormuser WHERE dormManId = ?";
            conn = DBUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);

            int affectedRows = pstmt.executeUpdate();

            Gson gson = new Gson();
            if (affectedRows > 0) {
                String jsonResponse = gson.toJson(new ResponseData(true, "删除成功"));
                response.getWriter().write(jsonResponse);
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                String jsonResponse = gson.toJson(new ResponseData(false, "用户未找到"));
                response.getWriter().write(jsonResponse);
            }
        } catch (NumberFormatException e) {
        } catch (Exception e) {
        }
    }

    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        handleCors(response);
        response.setContentType("application/json;charset=UTF-8");
        String pathInfo = request.getPathInfo();

        if (pathInfo == null || pathInfo.equals("/")) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Gson gson = new Gson();
            response.getWriter().write(gson.toJson(new ResponseData(false, "请求路径中必须包含用户ID")));
            return;
        }

        String id = pathInfo.substring(1);
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            int userId = Integer.parseInt(id);

            StringBuilder jsonBuilder = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }
            String json = jsonBuilder.toString();

            Gson gson = new Gson();
            User updatedUser = gson.fromJson(json, User.class);

            String sql = "UPDATE t_dormuser SET userName = ?, password = ?, dormBuildId = ? WHERE dormManId = ?";
            conn = DBUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, updatedUser.getUserName());
            pstmt.setString(2, updatedUser.getPassword());
            pstmt.setObject(3, updatedUser.getDormBuildId());
            pstmt.setInt(4, userId);

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                String jsonResponse = gson.toJson(new ResponseData(true, "用户更新成功"));
                response.getWriter().write(jsonResponse);
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                String jsonResponse = gson.toJson(new ResponseData(false, "用户未找到，无法更新"));
                response.getWriter().write(jsonResponse);
            }
        } catch (NumberFormatException e) {
        } catch (Exception e) {
        }
    }

    @Override
    protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        handleCors(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }

    private void handleCors(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Custom-Header");
    }
}